var express = require('express');
var router = express.Router();
var Question = require('../util/bean/questions').question;
/**
 * 获取所有的问题，url参数为page，类型为int
 */
router.get('/getAll',function (req,res,next) {
    let q = new Question();
    let page = parseInt(req.param('page'));
    q.findMany(page).then(function (data) {
        res.json(data);
    })
})
router.get('/getById',function (req,res,next) {
    let q = new Question();
    q._id = req.param('id');
    res.cookie('questionid',q._id);
    q.findById(q).then(function (data) {
        res.json(data);
    })
})

router.post('/getByIdToDetail',function (req,res,next) {
    let q = new Question();
    q._id = req.body.id;
    res.cookie('questionid',q._id);
    console.log('id',q._id);
    q.findById(q).then(function (data) {
        // res.json(data);
        console.log("answer------------->"+data);
        res.render("view/content",{"data":data});
    });
});

router.post('/upOne',function (req,res,next) {
    let title = req.body.title;
    let content = req.body.content;
    let owner = req.cookies._id;
    // console.log("title::::::::::::"+q.title);
    // console.log("content::::::::::"+q.content);
    // console.log("owner:::::::::::::::::::::::"+q.owner);
    if(title&&content&&owner){
        console.log("有东西了有东西了");
        let q = new Question();
        q.title = title;
        q.content = content;
        q.owner = owner;

        q.save(q).then(function (data) {
            res.json(data);
        });
    }else{
        res.json({result:'你要么没登录，要么信息没填写完整'})
    }
})
router.post('/answerOne',function (req,res) {
    let questionid = req.cookies.questionid;
    let cont = req.body.content;
    let own = req.cookies._id;
    console.log("title::::::::::::"+questionid);
    console.log("content::::::::::"+cont);
    console.log("owner:::::::::::::::::::::::"+own);
    let q = new Question();
    if(questionid&&own) {
        q._id = questionid;
        q.updateOneAnswer(q, {content: cont, owner: own}).then(function (data) {
            res.json(data);
        })
    }else {
        res.json({result:'no such cookie'})
    }
})

router.get('/findMyQuestions',function (req,res) {
    let q = new Question();
    if(req.cookies._id)
        q.findByOwnerId(req.cookies._id).then(function (data) {
            res.json(data);
        });
    else
        res.json({result:"请先登录"});
})

module.exports = router;